import { sport_data, sport_map } from './db_data';

async function changeStatus(stadiumId) {
  const state_id = await new Promise(resolve => {
    wx.showActionSheet({
      itemList: ['禁用', '启用'],
      success: (r) => resolve(r.tapIndex),
      fail: () => resolve(-1)
    })
  })
  if (state_id < 0) return;
  const res = await new Promise(resolve => {
    wx.cloud.callFunction({
      name: 'db_stadium',
      data: {
        funcName: 'update',
        stadium_id: stadiumId,
        updData: { stadium_state: state_id }
      },
      success: (r) => resolve(r.result),
      fail: () => resolve()
    });
  })
  if (!res) return;
  wx.showToast({
    title: `已更新 ${res.stats.updated} 条记录，请下拉刷新`,
    icon: 'none',
  })
}

async function editStadium(stadiumId) {
  wx.navigateTo({
    url: `/pages/creator/stadium?stadiumId=${stadiumId}`,
  })
}

async function search(searchText, searchData) {
  console.log('搜索字段：' + searchText);
  searchText = searchText.trim();
  const resList = await new Promise(resolve => {
    wx.cloud.callFunction({
      name: 'db_stadium',
      data: {
        funcName: 'query',
        searchText: searchText,
        searchData: searchData
      },
      success: (r) => resolve(r.result),
    });
  })
  return resList.map(o => {
    o.appointment_period = `可提前 ${o.appointment_period} 天预定`;
    o.stadium_state = ['已禁用', '已启用'][o.stadium_state];
    o.open_time = o.start_time + ' ~ ' + o.end_time;
    o.sport_names = o.sport_ids.map(v => sport_map.get(v)).join('，');
    return o;
  })
}

function manageCourt(stadiumId) {
  wx.navigateTo({
    url: `/pages/creator/court?stadiumId=${stadiumId}`,
  })
}

module.exports = {
  title: 'stadium_name',
  subtitle: 'stadium_state',
  data_keys: [
    { k: 'stadium_addr', v: '球馆地址' },
    { k: 'stadium_phone', v: '联系方式' },
    { k: 'stadium_desc', v: '球馆概述' },
    { k: 'appointment_period', v: '预约限制' },
    // 由数据映射得到该 key
    { k: 'open_time', v: '营业时间' },
    { k: 'sport_names', v: '包含的运动项目' }
  ],
  data_btns: [
    { label: '编辑', funcName: 'editStadium' },
    { label: '启用/禁用', funcName: 'changeStatus' },
    { label: '管理球场', funcName: 'manageCourt' }
  ],
  search_placeholder: '搜索球场名称，地址',
  header_btn: { text: '新建球馆', url: '/pages/creator/stadium' },
  tabs: [
    { label: '全部', searchData: {} },
    { label: '已启用', searchData: { stadium_state: 1 } },
    { label: '已禁用', searchData: { stadium_state: 0 } },
  ],
  editStadium,
  changeStatus,
  manageCourt,
  search,
}